//
//  GKManTableController.swift
//  MySwiftObject
//
//  Created by anscen on 2022/1/18.
//  Copyright © 2022 wangws1990. All rights reserved.
//

import UIKit

class GKManTableController: BaseTableViewController {
    public func setCommic(comicId :String, chapter :NSInteger,listChapter :[GKManChapter]){
        self.listChapter = listChapter
        self.comicId = comicId
        self.chapter = chapter
        self.currentChapter = chapter
        if self.listChapter.count > 0 {
            self.listData.removeAll()
            self.loadData(page:0, need: true)
        }else{
            self.endRefreshFailure()
        }
    }
    private lazy var listChapter : [GKManChapter] = {
        return []
    }()
    private lazy var listData : [GKManContent] = {
        return []
    }()
    private var comicId :String?    = nil
    private var currentChapter :Int = 0
    private var chapter :Int        = 0
    override func viewDidLoad() {
        super.viewDidLoad()
        self.loadUI()
    }
    private func loadUI(){
        self.tableView.scrollsToTop = false
        if #available(iOS 11.0, *) {
            self.tableView.contentInsetAdjustmentBehavior = .never
        } else {

        }
        self.tableView.backgroundColor = UIColor.clear
        self.tableView.estimatedRowHeight = 0
        self.tableView.showsVerticalScrollIndicator = false
        self.tableView.decelerationRate = .fast
    }
    //MARK:1下拉 2、上拉 0、第一次
    override func refreshData(page: Int) {
        loadData(page: page)
    }
    func loadData(page :Int,need :Bool = false){
        let currentSize = self.tableView.contentSize;
        guard let comicId = self.comicId else { return }
        if self.listChapter.count == 0 {
            return
        }
        if(page == 1){
//            if self.chapter != self.currentChapter{
//                self.chapter = self.currentChapter
//            }
            self.chapter = self.chapter == 0 ? 0 : self.chapter - 1
        }else if(page > 1){
//            if self.chapter != self.currentChapter{
//                self.chapter = self.currentChapter
//            }
            self.chapter = self.listChapter.count > self.chapter + 1 ? self.chapter + 1 : self.chapter
        }
        if self.listChapter.count > self.chapter{
            let chap = self.listChapter[self.chapter]
            let haveData = self.listData.contains { content in
                return content.chapterId == chap.chapterId
            }
            if haveData {
               // self.tableView.reloadData()
                self.endRefreshFailure()
                return
            }
            if  self.isrefreshing {
                return
            }
            self.isrefreshing = true
            if need{
                MBProgressHUD.showHUD(self.view, canTap: true, animated: true)
            }
            GKManCache.getCache(comicId: comicId, chapterId: chap.chapterId) { content in
                MBProgressHUD.hideHUD(self.view, animated: true)
                if(page == 1){
                    self.insertData(content: content,size: currentSize)
                }else{
                    self.appendData(content: content)
                }
                self.endRefresh(more:(self.listChapter.count) > self.chapter)
            } failure: { error in
                MBProgressHUD.hideHUD(self.view, animated: true)
                self.endRefresh(more:(self.listChapter.count) > self.chapter)
            }
        }else{
            self.endRefreshFailure()
        }
        self.getBeforeData()
        self.getAfterdata()
    }
    private var isrefreshing :Bool = false
    func insertData(content :GKManContent,size :CGSize){
        //定位
        let height = content.contentHeight
        let haveData = self.listData.contains { info in
            return content.chapterId == info.chapterId
        }
        if !haveData {
            self.listData.insert(content, at: 0)
            self.tableView.reloadData()
            self.tableView.setContentOffset(CGPoint.init(x: 0, y: height), animated: false)
        }
        self.isrefreshing = false
    }
    func appendData(content :GKManContent){
        let haveData = self.listData.contains { info in
            return content.chapterId == info.chapterId
        }
        if !haveData {
            self.listData.append(content)
            self.tableView.reloadData()
        }
        self.isrefreshing = false
    }
    func getBeforeData(){
        let chapter = self.chapter - 1
        if chapter >= 0 && self.listChapter.count > chapter {
            let info = self.listChapter[chapter]
            self.loadData(info)
        }
    }
    func getAfterdata(){
        let chapter = self.chapter + 1
        if chapter >= 0 && listChapter.count > chapter {
            let info = listChapter[chapter]
            self.loadData(info)
        }
    }
    func loadData(_ chap :GKManChapter){
        guard let comicId = self.comicId else { return }
        let json = ApiCache.values(key: chap.chapterId).json
        if json.isEmpty && json.count == 0 {
            GKManCache.getCache(comicId: comicId, chapterId: chap.chapterId) { object in
                if let js = object.toJSON(){
                    ApiCache.set(object: js, key: chap.chapterId)
                }
            } failure: { error in
                
            }
        }
    }
    override func numberOfSections(in tableView: UITableView) -> Int {
        return self.listData.count
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let model = self.listData[section]
        guard let listData = model.image_list else { return 0 }
        return listData.count
    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let model = self.listData[indexPath.section]
        guard let listData = model.image_list else { return 0.0 }
        let item = listData[indexPath.row]
        return item.cellHeight
    }
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if self.listData.count == section + 1 && self.listChapter.count > self.listData.count{
            return 25
        }
        return 0.01
    }
    override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 25))
        button.tag = section
        button.backgroundColor = UIColor.clear
        button.setTitleColor(UIColor.appx666666(), for: .normal)
        button.setTitle("正在加载下一章...", for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 13)
        button.isHidden = true;
        
        if self.listData.count == section + 1{
            button.isHidden = false
            if let last = self.listData.last{
                if let chap = self.listChapter.last{
                    button.isHidden = last.chapterId == chap.chapterId
                }
            }
        }
        return button
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = self.listData[indexPath.section]
        if let list = model.image_list{
            let cell = GKManCell.cellForTableView(tableView: tableView, indexPath: indexPath)
            cell.model = list[indexPath.row]
            return cell
        }
        return UITableViewCell.cellForTableView(tableView: tableView, indexPath: indexPath)
    }
    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        debugPrint("willDisplayHeaderView \(section)")
//        if section == 0 && self.listData.count > section{
//            let content = self.listData[section]
//            self.setModel(model: content, pageIndex: 0)
//        }
        if self.chapter == 0 && section <= 1{
            return
        }
        self.refreshData(page: 1)
    }
    func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
        debugPrint("willDisplayFooterView \(section)")
        self.loadFootData(section)
    }
    func loadFootData(_ section :Int){
        if self.chapter + 1 >= self.listChapter.count && section >= 1 {
            return
        }
        self.refreshData(page: 2)
    }
}
